﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using JohnnySins.DAL;
using JohnnySins.DAL.Repositories;
using JohnnySins.Entities;
using JohnnySins.Code;
using System.Web.Security;

namespace JohnnySins.Admin
{
    public partial class SiteMembers : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadCombo();
                LoadData();
            }
        }

        protected void LoadCombo()
        {
            using (var repo = RepositoryFactory.ResolveRepository<UserRepository>())
            {
                ddlCountryFilter.DataSource = repo.CountryCombo(false, true);
                ddlCountryFilter.DataBind();

                ddlPaymentTypeFilter.DataSource = repo.PaymentTypeCombo(false, true);
                ddlPaymentTypeFilter.DataBind();
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            LoadData();
        }

        protected void LoadData()
        {
            using (var repo = RepositoryFactory.ResolveRepository<UserRepository>())
            {
                grid.DataSource = repo.Search(txtNameFilter.Text, txtEmailFilter.Text, 
                        Convert.ToInt32(ddlPaymentTypeFilter.SelectedValue), 
                        Convert.ToInt32(ddlCountryFilter.SelectedValue), 
                        Convert.ToInt32(ddlIsActiveFilter.SelectedValue));
                grid.DataBind();
            }
        }

        protected void grid_RowDataBound(object sender, GridViewRowEventArgs e)
        {
        }

        protected void grid_Command(object sender, CommandEventArgs e)
        {
        }

        protected void grid_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grid.PageIndex = e.NewPageIndex;
            LoadData();
        }

        protected void btnSavePassword_Click(object sender, EventArgs e)
        {
            using (var repo = RepositoryFactory.ResolveRepository<UserRepository>())
            {
                User usr = repo.Find(Convert.ToInt32(hdUserId1.Value));
                if (usr == null) return;

                MembershipUser u = Membership.GetUser(usr.UserName);
                u.ChangePassword(usr.Password, tbPassword.Text);

                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "HideChange", "$('#passwordDialog').dialog('close'); alert('Password changed!');", true);
            }
        }
    }
}